package com.lkd.job;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lkd.common.VMSystem;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.service.VendingMachineService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.util.ShardingUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class XXLJob {
    @Autowired
    private VendingMachineService vendingMachineService;

    /**
     * 扫描所有运营中的售货机
     */
    @XxlJob("supplyJobHandler")
    public ReturnT<String> supplyJobHandler(String param) throws Exception{
        //实现任务分片
        ShardingUtil.ShardingVO shardingVo = ShardingUtil.getShardingVo();
        //分片总数
        int total = shardingVo.getTotal();
        //分片索引
        int index = shardingVo.getIndex();

        //扫描运营中的售货机
        LambdaQueryWrapper<VendingMachineEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VendingMachineEntity::getVmStatus, VMSystem.VM_STATUS_RUNNING).apply("mod(id,"+total+") = "+index);
        List<VendingMachineEntity> list = vendingMachineService.list(queryWrapper);

        for (VendingMachineEntity vmEntity : list) {
            //调用创建补货工单方法
            vendingMachineService.createSupplyTask(vmEntity.getInnerCode());
        }

        return ReturnT.SUCCESS;
    }
}
